package cn.softeem.tushu.web;

import cn.softeem.tushu.po.Book;
import cn.softeem.tushu.po.Cartitem;
import cn.softeem.tushu.po.User;
import cn.softeem.tushu.service.CartitemService;
import cn.softeem.tushu.service.Impl.CartitemServiceImpl;
import cn.softeem.tushu.utils.BaseServlet;
import cn.softeem.tushu.utils.BeanUtil;
import cn.softeem.tushu.utils.Tools;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


@WebServlet(name = "CartitemServlet", urlPatterns = "/CartitemServlet")
public class CartitemServlet extends BaseServlet {
    CartitemService cartitemService =new CartitemServiceImpl();
    public String myCart(HttpServletRequest request, HttpServletResponse response){
        User user = (User)request.getSession().getAttribute("user");
        String uid = user.getUid();
        List<Cartitem> list = cartitemService.myCart(uid);
        request.setAttribute("list",list);
        return  "f:/jsps/cart/list.jsp";
    }
    public String addCart(HttpServletRequest request, HttpServletResponse response){
        User user = (User)request.getSession().getAttribute("user");
        Book book = BeanUtil.toBeans(request.getParameterMap(),Book.class);
        Cartitem cartitem =BeanUtil.toBeans(request.getParameterMap(),Cartitem.class);
        cartitem.setCartItemId(Tools.uuid());
        cartitem.setBook(book);
        cartitem.setUser(user);
        cartitemService.addCart(cartitem);
        return  "f:/CartitemServlet?method=myCart";
    }
    public void updateQuantity(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        String cartItemId = req.getParameter("cartItemId");
        int quantity = Integer.parseInt(req.getParameter("quantity"));
        cartitemService.updateQuantity(cartItemId, quantity);

        String result = "{\"quantity\":" + quantity +  "}";
        resp.getWriter().print(result);
    }
    public String delete(HttpServletRequest request, HttpServletResponse response){
        String cartitemIds = request.getParameter("cartitemIds");
        cartitemService.delete(cartitemIds);
        return  "f:/CartitemServlet?method=myCart";
    }
    public String loadCartItems(HttpServletRequest request, HttpServletResponse response){
        String cartitemIds = request.getParameter("cartitemIds");
        List<Cartitem> cartitems = cartitemService.loadCartItems(cartitemIds);
        request.setAttribute("list",cartitems);
        request.setAttribute("ids",cartitemIds);
        return "f:/jsps/cart/showitem.jsp";
    }
}
